One of the benefits of using R is the beautiful graphs that you can create easily. However, as sometimes you want to write a document in Word or PowerPoint or you need to collaborate with others who are using these programs, the need to export your figures becomes a hassle. Moreover, usually it will be as a non-editable picture. Lately, I found the export package which allows you to export your graphs and outputs into a nice and neat editable office objects.

We should start by installing the package from CRAN:

install.packages("export")

Another alternative is to use the dev. version from github (make sure you have all the dependencies up to date):

install.packages("officer")
install.packages("rvg")
install.packages("openxlsx")
install.packages("ggplot2")
install.packages("flextable")
install.packages("xtable")
install.packages("rgl")
install.packages("stargazer")
install.packages("tikzDevice")
install.packages("xml2")
install.packages("broom")
install.packages("devtools")
library(devtools)
devtools::install_github("tomwenseleers/export")

Great, now lets load the package and see the functions we have:

library(export)

ls("package:export") 
##  [1] "graph2bitmap"      "graph2doc"         "graph2eps"        
##  [4] "graph2jpg"         "graph2office"      "graph2pdf"        
##  [7] "graph2png"         "graph2ppt"         "graph2svg"        
## [10] "graph2tif"         "graph2vector"      "rgl2bitmap"       
## [13] "rgl2png"           "table2csv"         "table2csv2"       
## [16] "table2doc"         "table2excel"       "table2html"       
## [19] "table2office"      "table2ppt"         "table2spreadsheet"
## [22] "table2tex"

We can see a certain pattern of what to format. Thus, we can export for example graphs to pictures (bitmap, jpg, png, tif) or to office documents (PowerPoint, Excel, Word).

Let's create an example graph and start the exporting. We'll be using the iris data-set.

library(tidyverse)
## -- Attaching packages ----------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.0     v purrr   0.3.4
## v tibble  3.0.1     v dplyr   1.0.0
## v tidyr   1.0.2     v stringr 1.4.0
## v readr   1.3.1     v forcats 0.5.0
## -- Conflicts -------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
graph <- iris %>% 
  ggplot(aes(Species, Sepal.Length)) + 
  geom_boxplot()
  
graph

And exporting to PowerPoint:

graph2ppt(graph, file = "myGraph.pptx")

As can be seen in the gif below, the exported graph come as a grouped fully editable object:

Same can be done to word:

graph2doc(graph, file = "myGraph.docx")

We can also create a table or output and export it.

fit <- lm(Sepal.Length ~ Petal.Length*Petal.Width, data = iris)

summary(fit)
## 
## Call:
## lm(formula = Sepal.Length ~ Petal.Length * Petal.Width, data = iris)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -1.00058 -0.25209  0.00766  0.21640  0.89542 
## 
## Coefficients:
##                          Estimate Std. Error t value Pr(>|t|)    
## (Intercept)               4.57717    0.11195  40.885  < 2e-16 ***
## Petal.Length              0.44168    0.06551   6.742 3.38e-10 ***
## Petal.Width              -1.23932    0.21937  -5.649 8.16e-08 ***
## Petal.Length:Petal.Width  0.18859    0.03357   5.617 9.50e-08 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.3667 on 146 degrees of freedom
## Multiple R-squared:  0.8078, Adjusted R-squared:  0.8039 
## F-statistic: 204.5 on 3 and 146 DF,  p-value: < 2.2e-16

Into Excel:

table2excel(summary(fit), file = "fit.xlsx")

Lastly, lets say we created a number of graphs and we want them slide after slide in a PowerPoint slide show, how can we do that?

First we create the graphs:

manyGraphs <- iris %>% 
  nest(-Species) %>% 
  mutate(
    graph = purrr::map2(
    .x = data,
    .y = Species, 
    .f = function(x, y) { 
      x %>% 
        ggplot(aes(Sepal.Width, Sepal.Length)) + 
        geom_point() + 
        geom_smooth(method = "lm") + 
        ggtitle(y)}))
## Warning: All elements of `...` must be named.
## Did you want `data = c(Sepal.Length, Sepal.Width, Petal.Length, Petal.Width)`?
manyGraphs
## # A tibble: 3 x 3
##   Species    data              graph 
##   <fct>      <list>            <list>
## 1 setosa     <tibble [50 x 4]> <gg>  
## 2 versicolor <tibble [50 x 4]> <gg>  
## 3 virginica  <tibble [50 x 4]> <gg>

Now, we can loop over the graphs and add them into the same presentation but in different slides:

for (i in 1:length(manyGraphs$graph)) {
  graphics.off()
  print(manyGraphs$graph[[i]])
  export::graph2ppt(
    file="myPlotsInPPT.pptx", 
    width=10,
    aspectr=sqrt(2),
    append=TRUE)
  graphics.off()
}

Thank you for reading!

Cheers, Amir